import { fileURLToPath, URL } from 'node:url';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import vueDevTools from 'vite-plugin-vue-devtools';
import autoprefixer from 'autoprefixer';
import cssnano from 'cssnano';
import postcssPxtorem from 'postcss-pxtorem';
import type { PreRenderedAsset } from 'rollup';
// https://vite.dev/config/

const viteConfig = (configEnv: ConfigEnv) => {
    const { mode } = configEnv;
    const env = loadEnv(mode, process.cwd(), '');
    return {
        plugins: [vue(), vueJsx(), vueDevTools()],
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            },
        },
        css: {
            postcss: {
                plugins: [
                    autoprefixer({
                        overrideBrowserslist: ['> 1%', 'last 2 versions', 'not dead'],
                    }),
                    cssnano(),
                    postcssPxtorem({
                        rootValue: 192,
                        propList: ['*', '!border'],
                    }),
                ],
            },
        },
        server: {
            host: '0.0.0.0',
            port: parseInt(env.VITE_APP_PORT, 10) || 9000,
            open: false,
            proxy: {
                '/api':{
                    target: env.VITE_API_BASE_URL || 'http://127.0.0.1:8080',
                    changeOrigin: true,
                }
            },
        },
        build: {
            outDir: 'dist',
            assetsInlineLimit: 0,
            emptyOutDir: true,
            rollupOptions: {
                input: {
                    main: fileURLToPath(new URL('./index.html', import.meta.url)),
                },
                output: {
                    entryFileNames: 'js/[name]-[hash].js',
                    chunkFileNames: 'js/[name]-[hash].js',
                    assetFileNames: (assetsInfo: PreRenderedAsset) => {
                        if (!assetsInfo.name) return 'assets/[name]-[hash].[ext]';

                        const imageEnd = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'];
                        const ext = assetsInfo.name.split('.').pop()?.toLowerCase() || '';

                        if (assetsInfo.name.endsWith('.css')) return 'css/[name]-[hash].css';
                        if (imageEnd.includes(ext)) {
                            return 'images/[name]-[hash].[ext]';
                        } else {
                            return 'assets/[name]-[hash].[ext]';
                        }
                    },
                },
            },
        },
    };
};

export default defineConfig(viteConfig);
